#include <Arduino.h>
#include <ShiftIn.h>
#include <BleCombo.h>
#include <duktape.h>
#include "KeyBoard_conf.h"
#include "Transmit.h"
#include "LVGLDisplayToLCD.h"
#include "AiEsp32RotaryEncoder.h"

ShiftIn<1> shiftRegister;
TaskHandle_t KeyboardFlash;
TaskHandle_t EnCoderFlash;
AiEsp32RotaryEncoder rotaryEncoder = AiEsp32RotaryEncoder(ENCODER_CLK, ENCODER_DT, ENCODER_SW, -1);

void KeyboardFlashTask(void *parameter)
{

  for (;;)
  {
    if (shiftRegister.update())
    {
      shiftRegister.operateChangedKey();
    }
    CMDOperateReceived();
    js_eval("keyboard_releaseAll");
  }
}

void EnCoderFlashTask(void *parameter)
{
  for (;;)
  {
    EncoderOperation(rotaryEncoder);
  }
}

void setup_74HC165()
{
  shiftRegister.begin(SCAN_PL, SCAN_CE, _74H_SPI_MISO, SCAN_SPI_CLK);
}

void setup()
{
  Serial.begin(115200);

  setup_74HC165();
  setup_Transmit();
  lv_obj_set_style_bg_color(lv_screen_active(), lv_color_hex(0x003a57), LV_PART_MAIN);

  rotaryEncoder.begin();
  rotaryEncoder.setup([]
                      { rotaryEncoder.readEncoder_ISR(); });
  // optionally we can set boundaries and if values should cycle or not
  rotaryEncoder.setBoundaries(0, 10, true); // minValue, maxValue, cycle values (when max go to min and vice versa)

  xTaskCreatePinnedToCore(KeyboardFlashTask, "Keyboard Flash", 10000, NULL, 1, &KeyboardFlash, 0);
  xTaskCreatePinnedToCore(EnCoderFlashTask, "EnCoderFlashTask", 10000, NULL, 1, &EnCoderFlash, 1);
}